﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo2
{
public class PathNavigator : System.Web.UI.Control
{
    private System.Collections.Generic.Stack<string> Prevs
        = new Stack<string>();

    private System.Collections.Generic.Stack<string> Nexts
        = new Stack<string>();

    private string currentPath;

    public string Path
    {
        get { return this.currentPath; }
    }

    public PathNavigator()
    {
    }

    public PathNavigator(string current)
    {
        this.currentPath = current;
    }

    public void Enter(string path)
    {
        if (this.currentPath == null)
        {
            this.currentPath = path;
            return;
        }

        this.Prevs.Push(this.currentPath);
        this.currentPath = path;
        this.Nexts.Clear();
    }

    public string Next()
    {
        if (this.Nexts.Count == 0)
        {
            throw new InvalidOperationException("后继中没有内容！");
        }
        this.Prevs.Push(this.currentPath);
        this.currentPath = this.Nexts.Pop();
        return this.currentPath;
    }

    public string Prev()
    {
        if (this.Prevs.Count == 0)
        {
            throw new InvalidOperationException("前面内容内容！");
        }

        this.Nexts.Push(this.currentPath);
        this.currentPath = this.Prevs.Pop();
        return this.currentPath;
    }


    #region IStateManager 成员


    protected override void LoadViewState(object state)
    {
        System.Web.UI.Triplet triplet
            = state as System.Web.UI.Triplet;
        if (triplet != null)
        {
            this.Prevs.Clear();
            this.Nexts.Clear();
            this.currentPath = triplet.Third as string;

            // 后面的是最里面的
            string[] prevsArray = triplet.First as string[];
            for (int i = prevsArray.Length - 1; i >= 0; i--)
            {
                this.Prevs.Push(prevsArray[i]);
            }

            string[] nextsArray = triplet.Second as string[];
            for (int i = nextsArray.Length - 1; i >= 0; i--)
            {
                this.Nexts.Push(nextsArray[i]);
            }
        }
    }

    protected override object SaveViewState()
    {
        // 按后进先出的顺序将元素复制到数组，类似于连续调用 Pop 所返回的元素的顺序。
        string[] prevs = this.Prevs.ToArray();
        string[] nexts = this.Nexts.ToArray();

        System.Web.UI.Triplet triplet
            = new System.Web.UI.Triplet();
        triplet.First = prevs;
        triplet.Second = nexts;
        triplet.Third = this.currentPath;

        return triplet;
    }


    #endregion
}
}
